﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace LingDingSoft.Http
{
    public class MultipartBodyWriter : IBodyWriter
    {
        private ICollection<KeyValuePair<string, string>>  _requestParams;
        private Encoding _coding;
        public MultipartBodyWriter(ICollection<KeyValuePair<string, string>> requestParams, Encoding coding)
        {
            _requestParams = requestParams;
            _coding = coding;

        }
        public MultipartBodyWriter(ICollection<KeyValuePair<string, string>> requestParams)
        {
            _requestParams = requestParams;
            _coding = AppConfig.GetEncoding();

        }
        public void Writer(HttpWebRequest request)
        {

            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            var beginBoundary = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            var endBoundary = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); 
            request.ContentType = "multipart/form-data; boundary=" + boundary;
             
            var strBuf = new StringBuilder();
            if (_requestParams!=null)
            {
                foreach (var key in _requestParams)
                {
                    strBuf.Append("\r\n--" + boundary + "\r\n");
                    strBuf.Append("Content-Disposition: form-data; name=\"" + key.Key + "\"\r\n\r\n");
                    strBuf.Append(key.Value.ToString());
                }
            }

            request.Method = "post";
            var requestStream = request.GetRequestStream();
            var tempBuffer = _coding.GetBytes(strBuf.ToString());
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();
             
        }
    }
}
